import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an48 from '@mmstudio/an000048';
import getuser from '../../../../atoms/getuser';
import { tbdict } from '../../../../atoms/db';


const logger = anylogger('pages/api/admin/dictsys/query.api');

export type IData = ITbdict & {
	type: string;
	name: string;
	key: number;
	value: string;
};


export type Result = {
	count: number;
	data: IData[];
};

export type Query = {
	q: string;
	page: string;
	pagesize: string;
}

/**
 * 值列维护查询
 */
const handler = an48<Result>();

handler.get(async (req, res) => {
	try {
		logger.debug('msg query:', req.query);
		const { q, ...rest } = req.query as Query;
		const page = Number(rest.page || '1');
		const pagesize = Number(rest.pagesize || '10');
		//验证管理员用户
		const user = await getuser(req);
		if (user.role !== 'admin') {
			//便于列表使用，false '' undefined null 0
			res.status(200).json({
				count: 0,
				data: []
			});
			return;
		}

		//获取所有数据
		const dttable = tbdict();
		if (q) {
			const query = q.trim();
			dttable.where('name', 'like', `%${query}%`)
				.orWhere('value', 'like', `%${query}%`);
		}

		//分页
		const [{ size }] = await dttable.count('*', { as: 'size' });
		const count = Number(size);
		const dttab = tbdict();
		if (q) {
			const query = q.trim();
			dttab.where('name', 'like', `%${query}%`)
				.orWhere('value', 'like', `%${query}%`);
		}
		const offset = (page - 1) * pagesize;
		const d = await dttab.select('*')
			.limit(pagesize)
			.offset(offset)
			.orderBy('type', 'asc')
			.orderBy('key', 'asc');
		const data = d.map((it) => {
			return {
				...it
			} as IData;
		});
		res.status(200).json({ data, count });
	} catch (error) {
		logger.trace(error);
		logger.error(error);
		res.status(200).json({
			count: 0,
			data: []
		});
	}
});

export const config = {} as PageConfig;

export default handler;
